package rnn.utilities;

import rnn.RNN;

public class CentroidCluster extends Element {

	public float[] centroid;
	public float centroidLength;	

	public CentroidCluster(float[] point) {
		this.points = new float[1][];
		this.points[0] = point;
		centroid = point;
		centroidLength=0;
		for (int i = 0; i < centroid.length; i++) {			
			centroidLength+=Math.pow(centroid[i],2);
		}
		centroidLength=(float) Math.sqrt(centroidLength);
	}

	public CentroidCluster(float[][] listPoints) {
		this.points = listPoints;

		centroid = new float[listPoints[0].length];
		for (int pIndex = 0; pIndex < listPoints.length; pIndex++) {
			float[] point = listPoints[pIndex];
			for (int i = 0; i < centroid.length; i++) {
				centroid[i] += point[i];				
			}			
		}
		
		centroidLength=0;
		for (int i = 0; i < centroid.length; i++) {
			centroid[i] /= (float)listPoints.length;
			centroidLength+=Math.pow(centroid[i],2);
		}
		centroidLength=(float) Math.sqrt(centroidLength);
	}

	public CentroidCluster(float[][] listPoints, float[] centroid) {
		this.points = listPoints;

		this.centroid = centroid;
		
		centroidLength=0;
		for (int i = 0; i < centroid.length; i++) {			
			centroidLength+=Math.pow(centroid[i],2);
		}
		centroidLength=(float) Math.sqrt(centroidLength);
	}

	@Override
	public float sim(Element cluster) {
		CentroidCluster c = (CentroidCluster) cluster;

		return sim(c.centroid,c.centroidLength, centroid, centroidLength);
	}

	public CentroidCluster agglomerate(Element cluster) {
		CentroidCluster c1 = (CentroidCluster) cluster;
		float[][] newPointsList = new float[c1.points.length
				+ points.length][];

		System.arraycopy(c1.points, 0, newPointsList, 0, c1.points.length);
		System.arraycopy(points, 0, newPointsList, c1.points.length,
				points.length);

		float[] newCentroid = new float[centroid.length];
		float sum = c1.points.length + points.length;
		for (int i = 0; i < centroid.length; i++) {
			newCentroid[i] += c1.points.length * c1.centroid[i]
					+ points.length * centroid[i];
			newCentroid[i] /= sum;
		}

		CentroidCluster c = new CentroidCluster(newPointsList, newCentroid);

//		System.out.println("agglomerate to " + newPointsList.length);
		return c;
	}

	@Override
	public String toString() {
		String txt = "size: " + points.length + "\n";
		// txt += Arrays.toString(centroid)+"\n";
		// for (float[] f : points) {
		// txt += "\t" + Arrays.toString(f) + "\n";
		// }

		return txt;
	}
}